import Koarouter from 'koa-router';
import md5 from 'md5';

import {checkBody, checkParam, paramTypeReg} from '../Util/KoaRouterParamChecker';
import {Users} from '../SQLmodules/user';

import {clients} from '../Client/main';

var md5salt = "Wei le ai ze la si";

var userRouter = new Koarouter();

userRouter.post('/login', checkBody({
  nick: paramTypeReg.USERNAME_DEFAULT,
  pwd:  paramTypeReg.PASSWORD_DEFAULT
}), async ctx=>{
  var ret = await Users.findOne({
    attributes:['id'],
    where:{
      nick: ctx.request.body.nick,
      password: md5(ctx.request.body.pwd + md5salt)
    }
  })

  if (ret){
    ctx.body = {
      id: ret.dataValues.id,
      token: clients.createToken(ret.dataValues.id)
    }
  }else{
    ctx.throw(201, "login failed");
  } 
})

userRouter.post('/register/:nick/:pwd', checkParam({
  nick: paramTypeReg.USERNAME_DEFAULT,
  pwd:  paramTypeReg.PASSWORD_DEFAULT
}), async ctx=>{
  var ret = await Users.create({
    nick: ctx.params.nick,
    password: md5(ctx.params.pwd + md5salt)
  });
  ctx.body = {
    id: ret.dataValues.id
  }
})

userRouter.post('/test', checkBody({
  token: paramTypeReg.STRING
}), async ctx=>{

  setInterval(
    ()=>{clients.emit(ctx.request.body.token, "hehe", {
      "hehe":1
    })}, 1000
  );

  ctx.body = {
    ok:1
  }
})

export default userRouter;